package com.btm.mcp.business.controller;

import com.btm.mcp.business.model.BusinessTerm;
import com.btm.common.model.PageResult;
import com.btm.mcp.business.service.BusinessTermService;
import com.meilisearch.sdk.exceptions.MeilisearchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/business-terms")
public class BusinessTermController {

    private final BusinessTermService businessTermService;

    public BusinessTermController(BusinessTermService businessTermService) {
        this.businessTermService = businessTermService;
    }

    @GetMapping("/get")
    public ResponseEntity<PageResult<BusinessTerm>> getTerms(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            PageResult<BusinessTerm> result;
            if (keyword == null || keyword.isEmpty()) {
                result = businessTermService.getAllTerms(page, size);
            } else {
                result = businessTermService.searchTerms(keyword, page, size);
            }
            return ResponseEntity.ok(result);
        } catch (MeilisearchException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PostMapping("/add")
    public ResponseEntity<BusinessTerm> addTerm(@RequestBody BusinessTerm term) {
        try {
            BusinessTerm newTerm = businessTermService.addTerm(term);
            return ResponseEntity.status(HttpStatus.CREATED).body(newTerm);
        } catch (MeilisearchException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<BusinessTerm> updateTerm(@PathVariable String id, @RequestBody BusinessTerm term) {
        try {
            term.setId(id);
            BusinessTerm updatedTerm = businessTermService.updateTerm(term);
            if (updatedTerm != null) {
                return ResponseEntity.ok(updatedTerm);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (MeilisearchException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTerm(@PathVariable String id) {
        try {
            businessTermService.deleteTerm(id);
            return ResponseEntity.noContent().build();
        } catch (MeilisearchException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
} 